//
//  OAuthViewController.swift
//  ZTWeiboo
//
//  Created by mac on 15/8/14.
//  Copyright © 2015年 YYL. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController , UIWebViewDelegate{
    
    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        webView.delegate = self
        
        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func close(){
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.loadRequest(NSURLRequest(URL: NetworkTools.shareTools.oauthUrl()))
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {

        let urlString = request.URL!.absoluteString
        
        if !urlString.hasPrefix(NetworkTools.shareTools.redirectUri){
            return true
        }
        if let query = request.URL!.query where query.hasPrefix("code="){
            let code = query.substringFromIndex(advance(query.startIndex, "code=".characters.count))
            loadAccessToken(code)
        }else{
            close()
        }
        
        return true
    }
    
    private func loadAccessToken(code:String){
        NetworkTools.shareTools.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
                // 延时一段时间再关闭
                let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC))
                dispatch_after(when, dispatch_get_main_queue()) {
                    self.close()
                }
                
                return
            }
            print(result)
            let userAccount = UserAccount(dict:result!)
            print(userAccount)

        }
    }
    
}
